<template>
  <div class="home-view">
    <!-- 顶部导航栏（仅在有选中文档时显示） -->
    <div v-if="selectedDocument" class="document-header">
      <div class="header-left">
        <button @click="clearSelection" class="back-btn">
          ← 返回文档列表
        </button>
      </div>
      <div class="header-right">
        <router-link to="/favorites" class="favorites-link">
          ❤️ 我的收藏
        </router-link>
      </div>
    </div>

    <div class="layout-container">
      <div class="sidebar">
        <DocumentTree 
          ref="documentTreeRef"
          :current-space-id="currentSpaceId" 
          @space-select="onSpaceSelect"
          @document-create="onDocumentCreate"
        />
        <DocumentList
          ref="documentListRef"
          :space-id="currentSpaceId"
          @document-select="onDocumentSelect"
          @document-edit="onDocumentEdit"
          @document-delete="onDocumentDelete"
        />
      </div>
      <div class="content">
        <DocumentDetail 
          ref="documentDetailRef"
          :document="selectedDocument" 
          @edit="onDocumentEdit"
          @delete="onDocumentDelete"
          @select="onDocumentSelect"
          @refresh="onRefresh"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import DocumentTree from '../components/DocumentTree.vue'
import DocumentList from '../components/DocumentList.vue'
import DocumentDetail from '../components/DocumentDetail.vue'
import type { Document } from '../types/document'
import { documentApi } from '../services/api'
import { toast } from '../utils/message'

const selectedDocument = ref<Document | null>(null)
const currentSpaceId = ref<number | null>(null)
const documentTreeRef = ref()
const documentListRef = ref()
const documentDetailRef = ref()

const route = useRoute()
const router = useRouter()

// 空间选择处理
const onSpaceSelect = (spaceId: number) => {
  currentSpaceId.value = spaceId
  // 清除当前选中的文档，让用户从文档列表中重新选择
  selectedDocument.value = null
}

// 文档创建处理
const onDocumentCreate = (spaceId: number) => {
  currentSpaceId.value = spaceId
  // 这里可以打开文档创建界面或导航到创建页面
  console.log('创建文档，空间ID:', spaceId)
}

const onDocumentSelect = (document: Document) => {
  selectedDocument.value = document
  // 更新路由，带上文档ID
  if (route.params.id !== document.id.toString()) {
    router.push(`/doc/${document.id}`)
  }
}

const onDocumentEdit = async (editedDocument: Document) => {
  try {
    const updatedDocument = await documentApi.update(editedDocument.id, editedDocument)
    selectedDocument.value = updatedDocument
    toast.success('文档更新成功')
    
    // 刷新文档列表以显示更新
    if (documentListRef.value && documentListRef.value.refreshDocuments) {
      documentListRef.value.refreshDocuments()
    }
  } catch (error) {
    console.error('更新文档失败:', error)
    toast.error('更新文档失败')
  }
}

const onDocumentDelete = async (id: number) => {
  try {
    await documentApi.delete(id)
    toast.success('文档删除成功')
    
    // 如果删除的是当前选中的文档，清除选择并导航回首页
    if (selectedDocument.value && selectedDocument.value.id === id) {
      selectedDocument.value = null
      router.push('/')
    }
    
    // 刷新文档列表
    if (documentListRef.value && documentListRef.value.refreshDocuments) {
      documentListRef.value.refreshDocuments()
    }
  } catch (error) {
    console.error('删除文档失败:', error)
    toast.error('删除文档失败')
  }
}

const onRefresh = () => {
  // 如果有选中的文档，重新加载它
  if (selectedDocument.value) {
    loadDocumentFromRoute()
  }
  
  // 刷新空间列表
  if (documentTreeRef.value && documentTreeRef.value.refreshSpaces) {
    documentTreeRef.value.refreshSpaces()
  }
}

// 清除文档选择
const clearSelection = () => {
  selectedDocument.value = null
  router.push('/')
}

// 根据路由参数加载文档
const loadDocumentFromRoute = async () => {
  const docId = route.params.id
  
  if (docId && typeof docId === 'string') {
    try {
      const document = await documentApi.getById(parseInt(docId))
      selectedDocument.value = document
      
      // 如果文档有namespaceId，设置当前空间
      if (document.namespaceId && document.namespaceId !== currentSpaceId.value) {
        currentSpaceId.value = document.namespaceId
      }
    } catch (error) {
      console.error('加载文档失败:', error)
      toast.error('文档不存在或加载失败')
      // 如果文档不存在，清除选择并回到首页
      selectedDocument.value = null
      router.replace('/')
    }
  } else {
    selectedDocument.value = null
  }
}

// 监听路由变化
watch(() => route.params.id, () => {
  loadDocumentFromRoute()
})

// 组件挂载时加载文档
onMounted(() => {
  loadDocumentFromRoute()
})
</script>

<style scoped>
.home-view {
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.document-header {
  background: white;
  border-bottom: 1px solid #e1e1e1;
  padding: 1rem 2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.back-btn {
  color: #42b883;
  background: none;
  border: none;
  text-decoration: none;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  transition: all 0.2s;
  font-weight: 500;
  cursor: pointer;
  font-size: 1rem;
}

.favorites-link {
  color: #42b883;
  text-decoration: none;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  transition: all 0.2s;
  font-weight: 500;
}

.back-btn:hover, .favorites-link:hover {
  background: rgba(66, 184, 131, 0.1);
  color: #369870;
  text-decoration: none;
}

.layout-container {
  flex: 1;
  display: flex;
  min-height: 0;
}

.sidebar {
  width: 400px;
  flex-shrink: 0;
  background: white;
  border-right: 1px solid #e1e1e1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.content {
  flex: 1;
  background: white;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

@media (max-width: 1024px) {
  .layout-container {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
    height: 60vh;
    border-right: none;
    border-bottom: 1px solid #e1e1e1;
  }
  
  .content {
    flex: 1;
    min-height: 40vh;
  }
}

@media (max-width: 768px) {
  .document-header {
    padding: 1rem;
    flex-direction: column;
    gap: 0.5rem;
    align-items: flex-start;
  }
  
  .header-left, .header-right {
    width: 100%;
    display: flex;
    justify-content: center;
  }

  .sidebar {
    height: 50vh;
  }
  
  .content {
    min-height: 50vh;
  }
}

/* 深色主题支持 */
.dark .document-header {
  background: #2d2d2d;
  border-bottom-color: #3d3d3d;
}
</style>